define(['jquery','common'], function($,common){
    var upload = {
        //初始化
        onLoad: function(element){
            upload.onClick(element+' button.xf-btn-upload');
            upload.onPreview(element+' button.xf-btn-preview');
        },
        //监听上传按钮
        onClick: function(element){
            $(document).on("click", element, function(){
                //表单上传元素
                var target = $(this).data('target');
                //触发点击事件，弹出选择窗口
                $(target).click();
                //监听表单上传事件
                upload.onSubmit(target);
            });
        },
        //监听预览按钮
        onPreview: function(element){
            $(document).on("click", element, function(){
                var imgSrc = $($(this).data('target')).val();
                if(imgSrc){
                    common.modal('<img src="'+imgSrc+'" class="img-fluid rounded mx-auto d-block" alt="preview">');
                }else{
                    common.toast('<strong class="text-danger">请先上传图片</strong>',1000);
                }
            });
        },
        //AJAX上传事件
        onSubmit: function(elementFile){
            $(document).on("change", elementFile, function(){
                var uploadPath = $(this).data('path');
                var targetId   = $(this).data('target');
                var formObj    = $(this)[0].files[0];
                var formData   = new FormData();
                //上传参数KEY/VALUE
                formData.append("file",formObj);
                //AJAX上传
                $.ajax({
                    url: uploadPath,
                    type: 'post',
                    cache: false,
                    data: formData,
                    contentType: false,
                    processData: false,
                    beforeSend: function(xhr){
                        //common.toast('开始上传',500);
                        $(targetId).val('').attr('placeholder','上传中');
                    },
                    error: function(xhr,status,msg){
                        common.toast('连接失败',2000);
                    },
                    success: function(res,status,xhr){
                        if(res.code == 1){
                            $(targetId).val(res.data.cdnUrl);
                            $(elementFile).next('.xf-btn-preview').removeClass('d-none');
                        }else{
                            common.toast(res.msg,1000);
                        }
                    },
                    complete: function(xhr,status){
                        $(targetId).attr('placeholder','上传完毕');
                    }
                });
            });
        }
    };
    return upload;
});